package grimbo.goodwinfooty.server.mvc;

import grimbo.goodwinfooty.server.ByteUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.fileupload.FileItemStream;

/**
 * Handles multiple file parameters.
 */
public class MultipleFileItemStreamHandler implements FileItemStreamHandler {
	private Set fileParams;
	private Map fileBytes;

	public MultipleFileItemStreamHandler(Set fileParams) {
		if ((null == fileParams) || (fileParams.isEmpty())) {
			throw new IllegalArgumentException(
					"fileParams cannot be null or empty");
		}
		validateFileParams(fileParams);
		this.fileParams = fileParams;
		this.fileBytes = new HashMap();
	}

	private void validateFileParams(Set fileParams) {
		for (Iterator it = fileParams.iterator(); it.hasNext();) {
			String fileParam = (String) it.next();
			if ((null == fileParam) || ("".equals(fileParam.trim()))) {
				throw new IllegalArgumentException(
						"All file param names must be non-null and non-blank");
			}
		}
	}

	@Override
	public void handleFileItemStream(FileItemStream item) throws IOException {
		String name = item.getFieldName();
		if (!fileParams.contains(name)) {
			return;
		}

		if (!item.isFormField()) {
			InputStream in = item.openStream();
			byte[] bytes = ByteUtils.readStream(in);
			fileBytes.put(name, bytes);
		}
	}
}
